<template>
  <div>
    <van-cell
      v-for="(item, index) in list"
      :key="index"
      icon="search"
      @click="$emit('search', item)"
    >
    <template #title>
      <span v-html="highLight(item)"></span>
    </template>
    </van-cell>
  </div>
</template>

<script>
import { suggestionApi } from '@/api/Search'
import { debounce } from 'lodash'
export default {
  data() {
    return {
      list: [], // 存放搜索建议数据
      // str: '<span style="color:red">w</span>ebpack'
    }
  },
  props: {
    keywords: String
  },
  watch: {
    // keywords(val) {
    //   this.getSuggestion()
    // }
    // 注意：默认情况下组件首次加载不会触发watch的监听
    keywords: {
      handler: debounce(function(val) {
        this.getSuggestion()
      }, 500),
      // 开启immediate为true即可在组件首次加载的时候触发一次watch监听
      immediate: true
    }
  },
  // 注意：如果watch中开启了immediate为true则在created中不需要去调用搜索建议接口
  // created() {
  //   this.getSuggestion()
  // },
  methods: {
    // 搜索词高亮
    highLight(str) {
      if (typeof str !== 'string') return
      const reg = new RegExp(this.keywords, 'gi')
      const newStr = str.replace(reg, `<span style="color: red">${this.keywords}</span>`)
      return newStr
    },
    // 获取搜索建议数据
    async getSuggestion() {
      const { data } = await suggestionApi({
        q: this.keywords
      })
      console.log(data)
      this.list = data.data.options.filter(item => item !== null)
    }
  }
}
</script>

<style>
</style>